<template>
  <div class="captcha-btn-ct">
    <div class="" @click="fGetCaptcha" v-if="!isCountNum">{{innerTxt}}</div>
    <div class="disabled" v-if="isCountNum" >重新发送{{innerCountDown+"s"}}</div>
  </div>
</template>
<script>
/**
 * 获取验证码倒计时
 * @desc 获取验证码倒计时button
 * @author ZXY
 * @date 2019年01月02日
 * @param phoneNum 要验证的电话号码
 * @param countDown 计时的秒数,默认不填写是60秒
 * @param fGetCaptcha 点击回调函数
 *页面引入 //import captchaButton from '@/components/common/captcha-button.vue'
 * <captcha-button :phoneNum="'137263526374'" :countDown="12"  @fGetCaptcha='fGetCaptcha'></captcha-button>
 */
export default {
  props: ['phoneNum', 'countDown', 'disabled', 'imgValCode', 'currentVal'],
  data () {
    return {
      innerTxt: '获取验证码',
      innerCountDown: 60,
      isCountNum: false, // 是否处于计时中
      timer: 0
    }
  },
  mounted () {},
  components: {},
  watch: {
    lastIndex: function (val) {},
    innerScore: function (value) {
    }
  },
  created () {
    let _This = this
    _This.innerCountDown = _This.countDown || 60
  },
  computed: {},
  methods: {
    /**
     * 点击获取验证码
     */
    fGetCaptcha (index) {
      let _This = this
      let {phoneNum, currentVal, imgValCode} = _This
      currentVal = currentVal || ''
      imgValCode = imgValCode || ''

      let regex = /^1(3|4|5|6|7|8|9)\d{9}$/
      if (!regex.test(phoneNum)) {
        alert('请输入正确手机号码')
        _This.$emit('fGetCaptcha', false)
        return false
      }
      if (imgValCode.toLocaleLowerCase() !== currentVal.toLocaleLowerCase()) {
        alert('验证码错误')
        _This.$emit('fGetCaptcha', false)
        return false
      }
      clearInterval(_This.timer)
      _This.isCountNum = true
      _This.timer = setInterval(() => {
        _This.innerCountDown--
        if (_This.innerCountDown === 0) {
          _This.isCountNum = false
          _This.innerCountDown = _This.countDown || 60
          clearInterval(_This.timer)
        }
      }, 1000)
      _This.$emit('fGetCaptcha', true)
    }
  }
}
</script>

<style lang="scss" scoped>
.captcha-btn-ct{
  display: inline-block;
  width: 100%;
  height: 100%;
  .disabled{
     // background: #cccccc;
      color: #ffffff;
  }
}
</style>
